import json
import math
import os

import cv2
import numpy as np
from numpy import matrix
from scipy import ndimage

path = 'D:/BaiduNetdiskDownload/vin/vinxml'
img_path = 'D:/BaiduNetdiskDownload/vin/vinimg'

from tqdm import tqdm


#list_xml = os.listdir(path)
from xml.dom.minidom import parse
import xml.dom.minidom
import xml.etree.ElementTree as ET

pi = 3.14


def rotate(ps, m):
    pts = np.float32(ps).reshape([-1, 2])  # 要映射的点
    pts = np.hstack([pts, np.ones([len(pts), 1])]).T
    target_point = np.dot(m, pts)
    target_point = [[int(target_point[0][x]),int(target_point[1][x])] for x in range(len(target_point[0]))]
    return target_point

def rotate_img_and_point(img,points,angle,center_x,center_y,resize_rate=1.0):
    h,w,c = img.shape
    M = cv2.getRotationMatrix2D((center_x,center_y), angle, resize_rate)
    res_img = cv2.warpAffine(img, M, (w, h))
    out_points = rotate(points, M)
    return res_img,out_points

def rotate_point(points,angle,center_x,center_y,resize_rate=1.0):
    M = cv2.getRotationMatrix2D((center_x, center_y), angle, resize_rate)
    out_points = rotate(points, M)
    return  out_points




def imggcut(image,y0,y1,x0,x1):
    if y0<0:
        y0 = 0
    if y1<0:
        y1 = 0
    if x0< 0:
        x0=0
    if x1 <0:
        x1=0
    return image[y0:y1,x0:x1]
def ro(point1,point2,angel):
    cos = math.cos(angel)
    sin = math.sin(angel)
    tx = point2[0]-point1[0]
    ty = point2[1]-point1[1]

    distance = math.sqrt((point1[0]-point2[0])**2+(point1[1]-point2[1])**2)
    m1 = matrix([[cos, -1*sin, 0], [sin, cos, 0], [0, 0, 1]], dtype=float)
    m2 = matrix([[1,0,tx],[0,1,ty],[0,0,1]],dtype=float)
    m3 = matrix([[1,0,-1*tx],[0,1,-1*ty],[0,0,1]],dtype=float)
    p = matrix([[point2[0]],[point2[1]],[1]])
    print(m1,m2,m3)
    print(m1*m2*m3*p)

def chuli(list_xml):

    #path = './origin_up'
    print(len(list_xml))
    for i in range(len(list_xml)):
      #print(os.path.join(img_path,list_xml[i].split(".")[0] + ".jpg"))
      if os.path.exists(os.path.join(img_path,list_xml[i].split(".")[0] + ".jpg")):
        # 打开xml文档
        #print(list_xml[i])
        box = {"x1": 0, "y1": 0, "x2": 0, "y2": 0, "angle": 0}
        dom = xml.dom.minidom.parse(path + "/" + list_xml[i])

        # 得到文档元素对象
        root = dom.documentElement
        if len(root.getElementsByTagName('object'))>0:
            object = root.getElementsByTagName('object')[0]

            robndbox = object.getElementsByTagName('robndbox')[0]

            img_weight = int(root.getElementsByTagName('size')[0].getElementsByTagName('width')[0].childNodes[0].data)
            img_height = int(root.getElementsByTagName('size')[0].getElementsByTagName('height')[0].childNodes[0].data)
            # print(img_height,img_weight)
            cx = robndbox.getElementsByTagName('cx')[0]
            x0 = int(float(cx.childNodes[0].data))
            cy = robndbox.getElementsByTagName('cy')[0]
            y0 = int(float(cy.childNodes[0].data))
            w = int(float(robndbox.getElementsByTagName('w')[0].childNodes[0].data))
            h = int(float(robndbox.getElementsByTagName('h')[0].childNodes[0].data))
            # print(x0, y0, w, h)
            ori = {"x1": x0 - int(w / 2.0), "y1": y0 - int(h / 2.0), "x2": x0 + int(w / 2.0), "y2": y0 + int(h / 2.0)}

            box['angle'] = float(robndbox.getElementsByTagName('angle')[0].childNodes[0].data)
            # print(box['angle'],math.pi)
            img = cv2.imread(img_path + "/" + list_xml[i].split(".")[0] + ".jpg")

            # cv2.circle(img, (int(x0), int(y0)), 1, (0, 0, 255), 4)

            # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
            # cv2.imshow("object detection", img)
            if w < h:
                # image = ndimage.rotate(img, ((box['angle']) / math.pi * 180)+90.0)
                image, p = rotate_img_and_point(img, points=[x0, y0], angle=((box['angle']) / math.pi * 180) + 90.0,
                                                center_x=int(img_weight / 2.0), center_y=int(img_height / 2.0),
                                                resize_rate=1.0)
                # print("p",p)
                temp = w
                w = h
                h = temp
                # cv2.circle(image, (int(p[0][0]), int(p[0][1])), 1, (0,0,255), 4)
                # cv2.imshow("detecn", image)
                # image = imggcut(image,int(p[0][1])-int(w/2.0),int(p[0][1])+int(w/2.0),int(p[0][0])-int(h/2.0),int(p[0][0])+int(h/2.0))

                # cv2.imshow("detection", image)
            else:
                # image = ndimage.rotate(img, ((box['angle']) / math.pi * 180))
                # cos = math.cos((box['angle']) / math.pi)
                # sin = math.sin((box['angle']) / math.pi)
                # x = (x0 - int(img_weight / 2.0)) * cos - (y0 - int(img_height / 2.0)) * sin + int(img_weight / 2.0)
                # y = (x0 - int(img_weight / 2.0)) * sin + (y0 - int(img_height / 2.0)) * cos + int(img_height / 2.0)
                # cv2.circle(image, (int(x), int(y)), 1, (0, 0, 255), 4)
                # cv2.circle(image, (10,10), 1, (0, 0, 255), 4)
                image, p = rotate_img_and_point(img, points=[x0, y0], angle=((box['angle']) / math.pi * 180),
                                                center_x=int(img_weight / 2.0), center_y=int(img_height / 2.0),
                                                resize_rate=1.0)
            # print("p", p)

            # image = imggcut(image, int(p[0][1]) - int(h / 2.0),int(p[0][1]) + int(h / 2.0),
            #   int(p[0][0]) - int(w / 2.0),int(p[0][0]) + int(w / 2.0))

            lv = [[0.99,1.01],[0.98,1.02],[0.97,1.03],[0.96,1.04],[0.95,1.05]]
            res_sp = image.shape
            for num in lv:

                result_p = []
                if int((p[0][1] - int(h / 2.0)) * num[0]) < 0:
                    result_p.append(0)
                else:
                    result_p.append(int((p[0][1] - int(h / 2.0)) * num[0]))

                if int((p[0][1] + int(h / 2.0)) * num[1]) > res_sp[0]:
                    result_p.append(res_sp[0])
                else:
                    result_p.append(int((p[0][1] + int(h / 2.0)) * num[1]))

                if int((p[0][0] - int(w / 2.0)) * num[0]) < 0:
                    result_p.append(0)
                else:
                    result_p.append(int((p[0][0] - int(w / 2.0)) * num[0]))

                if int((p[0][0] + int(w / 2.0)) * num[1]) > res_sp[1]:
                    result_p.append(res_sp[1])
                else:
                    result_p.append(int((p[0][0] + int(w / 2.0)) * num[1]))

                img = image[result_p[0]:result_p[1], result_p[2]:result_p[3]]
                if img.size != 0:
                    cv2.imwrite("./cut_dir/" + list_xml[i].split(".")[0] + "_"+str(num[0])+".jpg", img)

                # cv2.circle(image, (int(p[0][0]), int(p[0][1])), 1, (0, 0, 255), 4)

                # cv2.imshow("detection", image)
                # print("1")
                # print("./cutdir/"+list_xml[i].split(".")[0]+".jpg")
                # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                # image = 255 - cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                #                                          cv2.THRESH_BINARY, 31, 11)







            image = image[result_p[0]:result_p[1], result_p[2]:result_p[3]]

            # cv2.circle(image, (int(p[0][0]), int(p[0][1])), 1, (0, 0, 255), 4)

            # cv2.imshow("detection", image)
            # print("1")
            # print("./cutdir/"+list_xml[i].split(".")[0]+".jpg")
            # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            # image = 255 - cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
            #                                          cv2.THRESH_BINARY, 31, 11)
            if image.size != 0:
                cv2.imwrite("./cut_dir/" + list_xml[i].split(".")[0] + ".jpg", image)
            # cv2.imshow("1", image)
            # cv2.waitKey()

            # cv2.waitKey()

def get_rec_img(xml_path,img_path,savepath):
    #list_xml = os.listdir(xml_path)
    list_img = os.listdir(img_path)

    for i in tqdm(range(len(list_img))):
        xml_name = list_img[i].split(".")[0] + ".xml"
        if os.path.exists(os.path.join(xml_path, xml_name)):
            # 打开xml文档
            # print(list_xml[i])
            box = {"x1": 0, "y1": 0, "x2": 0, "y2": 0, "angle": 0}
            dom = xml.dom.minidom.parse(os.path.join(xml_path, xml_name))

            # 得到文档元素对象
            root = dom.documentElement
            if len(root.getElementsByTagName('object')) > 0:
                object = root.getElementsByTagName('object')[0]
                if len(object.getElementsByTagName('robndbox')) == 0:
                    continue
                robndbox = object.getElementsByTagName('robndbox')[0]

                img_weight = int(
                    root.getElementsByTagName('size')[0].getElementsByTagName('width')[0].childNodes[0].data)
                img_height = int(
                    root.getElementsByTagName('size')[0].getElementsByTagName('height')[0].childNodes[0].data)
                # print(img_height,img_weight)
                cx = robndbox.getElementsByTagName('cx')[0]
                x0 = int(float(cx.childNodes[0].data))
                cy = robndbox.getElementsByTagName('cy')[0]
                y0 = int(float(cy.childNodes[0].data))
                w = int(float(robndbox.getElementsByTagName('w')[0].childNodes[0].data))
                h = int(float(robndbox.getElementsByTagName('h')[0].childNodes[0].data))
                # print(x0, y0, w, h)
                ori = {"x1": x0 - int(w / 2.0), "y1": y0 - int(h / 2.0), "x2": x0 + int(w / 2.0),
                       "y2": y0 + int(h / 2.0)}

                box['angle'] = float(robndbox.getElementsByTagName('angle')[0].childNodes[0].data)
                # print(box['angle'],math.pi)
                img = cv2.imread(os.path.join(img_path,list_img[i]))

                # cv2.circle(img, (int(x0), int(y0)), 1, (0, 0, 255), 4)

                # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
                # cv2.imshow("object detection", img)
                if w < h:
                    # image = ndimage.rotate(img, ((box['angle']) / math.pi * 180)+90.0)
                    image, p = rotate_img_and_point(img, points=[x0, y0], angle=((box['angle']) / math.pi * 180) + 90.0,
                                                    center_x=int(img_weight / 2.0), center_y=int(img_height / 2.0),
                                                    resize_rate=1.0)
                    # print("p",p)
                    temp = w
                    w = h
                    h = temp


                else:

                    image, p = rotate_img_and_point(img, points=[x0, y0], angle=((box['angle']) / math.pi * 180),
                                                    center_x=int(img_weight / 2.0), center_y=int(img_height / 2.0),
                                                    resize_rate=1.0)


                lv = [[1, 1]]
                res_sp = image.shape
                for num in lv:

                    result_p = []
                    if int((p[0][1] - int(h / 2.0)) * num[0]) < 0:
                        result_p.append(0)
                    else:
                        result_p.append(int((p[0][1] - int(h / 2.0)) * num[0]))

                    if int((p[0][1] + int(h / 2.0)) * num[1]) > res_sp[0]:
                        result_p.append(res_sp[0])
                    else:
                        result_p.append(int((p[0][1] + int(h / 2.0)) * num[1]))

                    if int((p[0][0] - int(w / 2.0)) * num[0]) < 0:
                        result_p.append(0)
                    else:
                        result_p.append(int((p[0][0] - int(w / 2.0)) * num[0]))

                    if int((p[0][0] + int(w / 2.0)) * num[1]) > res_sp[1]:
                        result_p.append(res_sp[1])
                    else:
                        result_p.append(int((p[0][0] + int(w / 2.0)) * num[1]))

                    img = image[result_p[0]:result_p[1], result_p[2]:result_p[3]]
                    if img.size != 0:
                        cv2.imwrite(os.path.join(savepath,list_img[i]), img)



                #image = image[result_p[0]:result_p[1], result_p[2]:result_p[3]]

                # cv2.circle(image, (int(p[0][0]), int(p[0][1])), 1, (0, 0, 255), 4)

                # cv2.imshow("detection", image)
                # print("1")
                # print("./cutdir/"+list_xml[i].split(".")[0]+".jpg")
                # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                # image = 255 - cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                #                                          cv2.THRESH_BINARY, 31, 11)
                #if image.size != 0:
                #    cv2.imwrite(os.path.join(savepath,list_img[i]), image)
                # cv2.imshow("1", image)
                # cv2.waitKey()

                # cv2.waitKey()



def chuli_img(list_img):
    imgpath = './origin_up'
    print(len(list_img))
    for i in range(len(list_img)):
        # print(os.path.join(img_path,list_xml[i].split(".")[0] + ".jpg"))
        if os.path.exists(os.path.join(imgpath,list_img[i])):
            # 打开xml文档
            # print(list_xml[i])
            box = {"x1": 0, "y1": 0, "x2": 0, "y2": 0, "angle": 0}
            dom = xml.dom.minidom.parse(path + "/" + list_img[i].split(".")[0]+".xml")

            # 得到文档元素对象
            root = dom.documentElement
            if len(root.getElementsByTagName('object')) > 0:
                object = root.getElementsByTagName('object')[0]

                robndbox = object.getElementsByTagName('robndbox')[0]

                img_weight = int(
                    root.getElementsByTagName('size')[0].getElementsByTagName('width')[0].childNodes[0].data)
                img_height = int(
                    root.getElementsByTagName('size')[0].getElementsByTagName('height')[0].childNodes[0].data)
                # print(img_height,img_weight)
                cx = robndbox.getElementsByTagName('cx')[0]
                x0 = int(float(cx.childNodes[0].data))
                cy = robndbox.getElementsByTagName('cy')[0]
                y0 = int(float(cy.childNodes[0].data))
                w = int(float(robndbox.getElementsByTagName('w')[0].childNodes[0].data))
                h = int(float(robndbox.getElementsByTagName('h')[0].childNodes[0].data))
                # print(x0, y0, w, h)
                ori = {"x1": x0 - int(w / 2.0), "y1": y0 - int(h / 2.0), "x2": x0 + int(w / 2.0),
                       "y2": y0 + int(h / 2.0)}

                box['angle'] = float(robndbox.getElementsByTagName('angle')[0].childNodes[0].data)
                # print(box['angle'],math.pi)
                img = cv2.imread(imgpath + "/" + list_img[i])

                # cv2.circle(img, (int(x0), int(y0)), 1, (0, 0, 255), 4)

                # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
                # cv2.imshow("object detection", img)
                if w < h:
                    # image = ndimage.rotate(img, ((box['angle']) / math.pi * 180)+90.0)
                    image, p = rotate_img_and_point(img, points=[x0, y0], angle=((box['angle']) / math.pi * 180) + 90.0,
                                                    center_x=int(img_weight / 2.0), center_y=int(img_height / 2.0),
                                                    resize_rate=1.0)
                    # print("p",p)
                    temp = w
                    w = h
                    h = temp
                    # cv2.circle(image, (int(p[0][0]), int(p[0][1])), 1, (0,0,255), 4)
                    # cv2.imshow("detecn", image)
                    # image = imggcut(image,int(p[0][1])-int(w/2.0),int(p[0][1])+int(w/2.0),int(p[0][0])-int(h/2.0),int(p[0][0])+int(h/2.0))

                    # cv2.imshow("detection", image)
                else:
                    # image = ndimage.rotate(img, ((box['angle']) / math.pi * 180))
                    # cos = math.cos((box['angle']) / math.pi)
                    # sin = math.sin((box['angle']) / math.pi)
                    # x = (x0 - int(img_weight / 2.0)) * cos - (y0 - int(img_height / 2.0)) * sin + int(img_weight / 2.0)
                    # y = (x0 - int(img_weight / 2.0)) * sin + (y0 - int(img_height / 2.0)) * cos + int(img_height / 2.0)
                    # cv2.circle(image, (int(x), int(y)), 1, (0, 0, 255), 4)
                    # cv2.circle(image, (10,10), 1, (0, 0, 255), 4)
                    image, p = rotate_img_and_point(img, points=[x0, y0], angle=((box['angle']) / math.pi * 180),
                                                    center_x=int(img_weight / 2.0), center_y=int(img_height / 2.0),
                                                    resize_rate=1.0)
                # print("p", p)

                # image = imggcut(image, int(p[0][1]) - int(h / 2.0),int(p[0][1]) + int(h / 2.0),
                #   int(p[0][0]) - int(w / 2.0),int(p[0][0]) + int(w / 2.0))

                lv = [[0.99, 1.01], [0.98, 1.02], [0.97, 1.03], [0.96, 1.04], [0.95, 1.05]]
                res_sp = image.shape
                for num in lv:

                    result_p = []
                    if int((p[0][1] - int(h / 2.0)) * num[0]) < 0:
                        result_p.append(0)
                    else:
                        result_p.append(int((p[0][1] - int(h / 2.0)) * num[0]))

                    if int((p[0][1] + int(h / 2.0)) * num[1]) > res_sp[0]:
                        result_p.append(res_sp[0])
                    else:
                        result_p.append(int((p[0][1] + int(h / 2.0)) * num[1]))

                    if int((p[0][0] - int(w / 2.0)) * num[0]) < 0:
                        result_p.append(0)
                    else:
                        result_p.append(int((p[0][0] - int(w / 2.0)) * num[0]))

                    if int((p[0][0] + int(w / 2.0)) * num[1]) > res_sp[1]:
                        result_p.append(res_sp[1])
                    else:
                        result_p.append(int((p[0][0] + int(w / 2.0)) * num[1]))

                    #img = image[result_p[0]:result_p[1], result_p[2]:result_p[3]]
                    cv2.circle(image, (int(p[0][0]), int(p[0][1])), 1, (0, 0, 255), 4)
                    cv2.circle(image, (int(result_p[2]), int(result_p[0])), 1, (0, 0, 255), 4)
                    cv2.circle(image, (int(result_p[3]), int(result_p[1])), 1, (0, 0, 255), 4)

                    if img.size != 0:
                        cv2.imshow("1", image)
                        cv2.waitKey()
                        cv2.destroyAllWindows()
                        #cv2.imwrite("./cut_dir/" + list_img[i].split(".")[0] + "_" + str(num[0]) + ".jpg", img)

                    # cv2.circle(image, (int(p[0][0]), int(p[0][1])), 1, (0, 0, 255), 4)

                    # cv2.imshow("detection", image)
                    # print("1")
                    # print("./cutdir/"+list_xml[i].split(".")[0]+".jpg")
                    # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                    # image = 255 - cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                    #                                          cv2.THRESH_BINARY, 31, 11)

                #image = image[result_p[0]:result_p[1], result_p[2]:result_p[3]]

                # cv2.circle(image, (int(p[0][0]), int(p[0][1])), 1, (0, 0, 255), 4)

                # cv2.imshow("detection", image)
                # print("1")
                # print("./cutdir/"+list_xml[i].split(".")[0]+".jpg")
                # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                # image = 255 - cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                #                                          cv2.THRESH_BINARY, 31, 11)
                #if image.size != 0:
                 #   cv2.imwrite("./cut_dir/" + list_img[i].split(".")[0] + ".jpg", image)
                # cv2.imshow("1", image)
                # cv2.waitKey()

                # cv2.waitKey()
def get_db(listxml,imgpath):
    f = open("db_net_train.txt", "w")
    #f_roc = open("roc_train.txt","w")
    path1 = '/home/hetao/PaddleOCR-release-2.1/train_data/db'
    list_xml = os.listdir(listxml)
    find = []
    for i in tqdm(range(len(list_xml))):
        find = []
        #print(list_xml[i])
        if os.path.exists(imgpath + "/" + list_xml[i].split(".")[0] + ".jpg") and os.path.exists(listxml+"/"+list_xml[i]):
            neirong = {"transcription": '', "points": []}
            neirong["transcription"] = list_xml[i].split(".")[0]
            dom = xml.dom.minidom.parse(listxml + "/" + list_xml[i])

            # 得到文档元素对象
            root = dom.documentElement
            if len(root.getElementsByTagName('object'))>0:



                object = root.getElementsByTagName('object')[0]

                if len(object.getElementsByTagName('robndbox')) ==0:
                    continue
                robndbox = object.getElementsByTagName('robndbox')[0]

                img_weight = int(
                    root.getElementsByTagName('size')[0].getElementsByTagName('width')[0].childNodes[0].data)
                img_height = int(
                    root.getElementsByTagName('size')[0].getElementsByTagName('height')[0].childNodes[0].data)
                # print(img_height,img_weight)
                cx = robndbox.getElementsByTagName('cx')[0]
                cy = robndbox.getElementsByTagName('cy')[0]
                x0 = int(float(cx.childNodes[0].data))
                y0 = int(float(cy.childNodes[0].data))
                w = int(float(robndbox.getElementsByTagName('w')[0].childNodes[0].data))
                h = int(float(robndbox.getElementsByTagName('h')[0].childNodes[0].data))
                angel = float(robndbox.getElementsByTagName('angle')[0].childNodes[0].data)
                if w > h:
                    points = {}
                    image = cv2.imread(imgpath + "/" + list_xml[i].split(".")[0] + ".jpg")
                    points['ys'] = rotate_point((x0 + float(w / 2.0), y0 - float(h / 2.0)),
                                                (-1) * angel / math.pi * 180, x0, y0, resize_rate=1.0)
                    points['yx'] = rotate_point((x0 + float(w / 2.0), y0 + float(h / 2.0)),
                                                (-1) * angel / math.pi * 180, x0, y0, resize_rate=1.0)
                    points['zs'] = rotate_point((x0 - float(w / 2.0), y0 - float(h / 2.0)),
                                                (-1) * angel / math.pi * 180, x0, y0,
                                                resize_rate=1.0)
                    points['zx'] = rotate_point((x0 - float(w / 2.0), y0 + float(h / 2.0)),
                                                (-1) * angel / math.pi * 180, x0, y0,
                                                resize_rate=1.0)
                    # print(points)
                    sort_by = sorted(points.items(), key=lambda d: d[1][0][1])
                    # sort_bx = sorted(points.items(), key=lambda d: d[1][0][0])
                    # print(sort_by)
                    sort = []
                    if sort_by[0][1][0][0] < sort_by[1][1][0][0]:
                        sort.append(sort_by[0][1][0])
                        sort.append(sort_by[1][1][0])
                    else:
                        sort.append(sort_by[1][1][0])
                        sort.append(sort_by[0][1][0])
                    if sort_by[2][1][0][0] < sort_by[3][1][0][0]:
                        sort.append(sort_by[3][1][0])
                        sort.append(sort_by[2][1][0])

                    else:
                        sort.append(sort_by[2][1][0])
                        sort.append(sort_by[3][1][0])
                    neirong['points'] = sort

                    f.write( path1 + "/train/" + list_xml[i].split(".")[0] + ".jpg" + "\t" + json.dumps([neirong]) + "\n")
                    #f_roc.write(path1 + "/train/" + list_xml[i].split(".")[0] + ".jpg" + "\t" + str(angel / math.pi * 180) + "\n")
                else:
                    temp = w
                    w = h
                    h = temp

                    points = {}
                    image = cv2.imread(imgpath + "/" + list_xml[i].split(".")[0] + ".jpg")
                    points['ys'] = rotate_point((x0 + float(w / 2.0), y0 - float(h / 2.0)),
                                                (-1) * (angel / math.pi * 180+90), x0, y0, resize_rate=1.0)
                    points['yx'] = rotate_point((x0 + float(w / 2.0), y0 + float(h / 2.0)),
                                                (-1) * (angel / math.pi * 180+90), x0, y0, resize_rate=1.0)
                    points['zs'] = rotate_point((x0 - float(w / 2.0), y0 - float(h / 2.0)),
                                                (-1) * (angel / math.pi * 180+90), x0, y0,
                                                resize_rate=1.0)
                    points['zx'] = rotate_point((x0 - float(w / 2.0), y0 + float(h / 2.0)),
                                                (-1) * (angel / math.pi * 180+90), x0, y0,
                                                resize_rate=1.0)
                    # print(points)
                    sort_by = sorted(points.items(), key=lambda d: d[1][0][1])
                    # sort_bx = sorted(points.items(), key=lambda d: d[1][0][0])
                    # print(sort_by)
                    sort = []
                    if sort_by[0][1][0][0] < sort_by[1][1][0][0]:
                        sort.append(sort_by[0][1][0])
                        sort.append(sort_by[1][1][0])
                    else:
                        sort.append(sort_by[1][1][0])
                        sort.append(sort_by[0][1][0])
                    if sort_by[2][1][0][0] < sort_by[3][1][0][0]:
                        sort.append(sort_by[3][1][0])
                        sort.append(sort_by[2][1][0])

                    else:
                        sort.append(sort_by[2][1][0])
                        sort.append(sort_by[3][1][0])
                    neirong['points'] = sort
                    #print("neirong", neirong)
                    f.write(
                        path1 + "/train/" + list_xml[i].split(".")[0] + ".jpg" + "\t" + json.dumps([neirong]) + "\n")


                cv2.circle(image, (int(sort[0][0]), int(sort[0][1])), 1, (0, 0, 255), 4)
                cv2.circle(image, (int(sort[1][0]), int(sort[1][1])), 1, (0, 0, 255), 4)
                cv2.circle(image, (int(sort[2][0]), int(sort[2][1])), 1, (0, 0, 255), 4)
                cv2.circle(image, (int(sort[3][0]), int(sort[3][1])), 1, (0, 0, 255), 4)

                cv2.imshow("1", image)
                cv2.waitKey()

    f.close()


                    #f_roc.write(path1 + "/train/" + list_xml[i].split(".")[0] + ".jpg" + "\t" + str(
                     #   angel / math.pi * 180) + "\n")

                 #print(path1+"/train/"+list_xml[i].split(".")[0] + ".jpg"+"\t"+str([neirong])+"\n")

                     #print(int(points[k][0][0]), int(points[k][0][1]))
                     #cv2.circle(image, (int(points[k][0][0]), int(points[k][0][1])), 1, (0, 0, 255), 4)







                 #cv2.imshow("1", image)
                 #cv2.waitKey()





'''
        max = w
        maxa = abs(math.sin(box['angle']))
        if max < h:
            max = h
        if maxa < abs(math.cos(box['angle'])):
            maxa = abs(math.cos(box['angle']))

        print(math.cos(box['angle']), math.sin(box['angle']))
        box['x1'] = x0 - int(max / 2.0 * abs(math.cos(box['angle'])))

        box["x2"] = x0 + int(max / 2.0 * abs(math.cos(box['angle'])))
        box["y1"] = y0 - int(max / 2.0 * abs(math.sin(box['angle'])))

        box["y2"] = y0 + int(max / 2.0 * abs(math.sin(box['angle'])))

        if box['x1'] < 0:
            box['x2'] = box['x2'] - abs(box['x1'])
            box['x1'] = 0
        if box['y1'] < 0:
            box['y2'] = box['y2'] - abs(box['y1'])
            box['y1'] = 0
            
'''
        #img = cv2.imread(img_path + "/" + list_xml[i].split(".")[0] + ".jpg")

        # cv2.imshow(" detection", img)
        #   if box['angle'] <0.5 and box['angle']>0.2 :
        #       img = ndimage.rotate(img, (box['angle']/1.5)*90+270)

        # if box['angle']>2.7 and box['angle']<3.3:
        #    img = ndimage.rotate(img, (box['angle']/3.0)*90)

        # print(((box['angle'])/pi*180))
        # img = ndimage.rotate(img, ((box['angle'])/pi*180))
        # cv2.imshow("object detection", img)
     #   image = img[box['y1']: box['y2'], box['x1']:box['x2']]


       # print(box)


def _xml(xmlpath,newpath):
    list_xml = os.listdir(xmlpath)
    dic = 0
    for i in range(len(list_xml)):
        find = []
        isWrong = False
        # print(list_xml[i])
        if  os.path.exists(xmlpath + "/" + list_xml[i]):
            print(list_xml[i])
            dom = xml.dom.minidom.parse(xmlpath + "/" + list_xml[i])

            # 得到文档元素对象
            root = dom.documentElement
            if len(root.getElementsByTagName('object')) > 0:
                object = root.getElementsByTagName('object')
                for ob in range(len(object)):
                    name = object[ob].getElementsByTagName('name')[0].childNodes[0].data

                    if name == 'persond':
                        dic = dic + 1
                        object[ob].getElementsByTagName('name')[0].childNodes[0].data = 'person'
                        isWrong = True
                if isWrong:
                    with open(os.path.join(newpath, list_xml[i]), 'w', encoding='utf-8') as fh:
                        dom.writexml(fh)

            print(dic)


#ro((50,50),(100,0),-1*math.pi/4)
#chuli_img(os.listdir('./origin_up'))
#get_db("D:/BaiduNetdiskDownload/vin_6.04/xml","D:/BaiduNetdiskDownload/vin_6.04/vin")
#print(rotate_point())
#_xml('D:/BaiduNetdiskDownload/dpry_0623_9200/dp/Annotations','./badxml')


get_rec_img('D:/BaiduNetdiskDownload/vin_6.28_roLabel/vin6.28/simple/xml','D:/BaiduNetdiskDownload/vin_6.28_roLabel/vin6.28/simple/1','E:/data/vin/rec')